<?php

namespace App\Models;

use App\Exceptions\InternalException;
use App\Service\ProductService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class ProductSku extends Model
{
    protected $fillable = ['price', 'stock'];

    protected $appends = ['spec_sku_name'];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function getImageAttribute($value)
    {
        if($value) {
            return config('upload.ossUrl').$value;
        }elseif (Str::contains($value, config('upload.ossUrl'))) {
            return $value;
        }  else{
            return '';
        }
    }

    public function getSpecSkuNameAttribute()
    {
        if(!is_null($this->getAttribute('spec_sku_id')))
        {
            $skus = app(ProductService::class)->getProductSkus($this->product);
            $id = $this->getAttribute('id');
            $res = collect($skus)->filter(function ($s) use ($id){
                return $s['id'] == $id;
            })->first();
            return $res['difference'];
        }else {
            return '';
        }
    }

    /**
     *  减少下单时的库存
     *
     * @param $amount
     * @return mixed
     * @throws InternalException
     */
    public function decreaseStock($amount)
    {
        if ($amount < 0) {
            throw new InternalException('减库存不可小于0');
        }
        return $this->where('id', $this->id)->where('stock', '>=', $amount)->decrement('stock', $amount);
    }

    /**
     * 增加库存
     *
     * @param $amount
     * @throws InternalException
     */
    public function addStock($amount)
    {
        if ($amount < 0) {
            throw new InternalException('加库存不可小于0');
        }
        $this->increment('stock', $amount);
    }
}
